const mongoose = koahub.mongoose;
const Schema = koahub.Schema;
const ObjectId = Schema.Types.ObjectId;
import {slugify} from 'transliteration';

let schema = new Schema({
    title: {
        type: String,
        required: true
    },
    pinyin: String,
    url: Boolean,
    cover: {
        type: ObjectId,
        ref: 'Picture',//关联File表的_id
    },
    category: {
        type: ObjectId,
        ref: 'Category' //关联Category表的_id
    },
    author: String,
    editor: [], //编辑，经过编辑的人列表
    body: String,
    abstract: String,
    tags: [],
    articleType: String,
    //  `type` int(11) NOT NULL COMMENT '0:最新资讯，1:推荐阅读，2:今日头条，3:电商经验谈',
    status: {type: Number, default: 0},
    rank: {type: Number, default: 0}, //排序
    meta: {
        favors: {type: Number, default: 0},
        visited: {type: Number, default: 0}
    }
}, {timestamps: {}, minimize: false,collection:'Article'});

schema.statics.findByTitle = function (title, cb) {
    return this.find({name: new RegExp(title, 'i')}, cb);
};

schema.virtual('comments').get(async function () {
    const Comment = koahub.model('admin/Comment');
    const comments = await Comment.find({
        rowId: this._id
    }).sort({createdAt: 'asc'}).populate('commenter').exec(); //计算关联的评论人信息
    return comments;
});

// schema.statics.findCommentsById = async function (id) {
//
//     const Comment = koahub.model('admin/Comment');
//     const comments = await Comment.find({
//         rowId: id
//     }).sort({createdAt: 'asc'}).populate('commenter').exec() //计算关联的评论人信息
//
// }


// 参数User 数据库中的集合名称, 不存在会创建.
let Article = mongoose.model('Article', schema);


//插入测试数据
Article.findOne(function (err, data) {
    if (!data) {
        const articleId = new koahub.mongoose.Types.ObjectId();

        Article.create({
            _id: articleId,
            title: '校园网络升级公告',
            pinyin: slugify('校园网络升级公告'),
            author: 'zengqs'

        });

        const Comment = koahub.model('admin/Comment');
        Comment.create({
            body: '评论内容1',
            model: 'Article',
            rowId: articleId,
            module:'admin',
            application:'system',
            commenter:'5a7718924b4e7f2869f450a9'
        });
        Comment.create({
            body: '评论内容2',
            model: 'Article',
            rowId: articleId,
            module:'admin',
            application:'system',
            commenter:'5a7718924b4e7f2869f450a9' //guset
        });
    }
});

module.exports = Article;